<?php
/**
 * Created by PhpStorm.
 * User: Lenovo
 * Date: 6/14/2018
 * Time: 21:39
 */

class Timer
{
    private $serv;
    public function __construct()
    {
        $this->serv = new swoole_server('0.0.0.0', 9501);
        $this->serv->set([
            'worker_num' => 8,
            'daemonize' => false,
            'max_request' => 10000,
            'dispatch_mode' => 2
        ]);
        $this->serv->on('Start', [$this, 'onStart']);
        $this->serv->on('Connect', [$this, 'onConnect']);
        $this->serv->on('Receive', [$this, 'onReceive']);
        $this->serv->on('Close', [$this, 'onClose']);
        //$this->serv->on('WorkerStart', [$this, 'onWorkerStart']);
        $this->serv->start();
    }

    public function onStart($serv)
    {
        //echo "Start\n";
    }

    public function onConnect($serv, $fd, $from_id)
    {
        //echo "Client {$fd} connect\n";
    }

    public function onClose($serv, $fd, $from_id)
    {
       // echo "Client {$fd} close connection\n";
    }

//    public function onWorkerStart($serv, $worker_id)
//    {
//        if ($worker_id == 0) {
//            swoole_timer_tick(1000, function ($timer_id, $params) {
//                echo "Timer running\n";
//                echo "recv: {$params}\n";
//            }, "Hello");
//        }
//    }
    // public function onWorkerStart($serv, $worker_id)
    // {
        // if ($worker_id == 0) {
            // swoole_timer_tick(1000, [$this, 'onTick'], "Hello");
        // }
    // }

    public function onReceive(swoole_server $serv, $fd, $from_id, $data)
    {
		swoole_timer_after(86400000, function() use ($data) {
			$pdo = new PDO("mysql:host=106.14.226.58;dbname=newproject-sanka;port=3307", "root", "caoshijie_sikao", array(PDO::ATTR_PERSISTENT => true));
			$waybill = $pdo->query("select status from lv_waybills where id=".$data);
			$w = $waybill->fetch(PDO::FETCH_ASSOC);
			if($w['status'] == 1){
				$sql = "update lv_waybills set status=0 where id=".$data;
				$res = $pdo->exec($sql);
				if($res){
					echo "执行成功";
				}else{
					echo "执行失败";
				}
			}
		});
        
//        echo "Get Message From Client {$fd}:{$data}\n";
//        swoole_timer_after(1000, function () use ($serv, $fd) {
//            echo "Timer after\n";
//            $serv->send($fd, "Hello later\n");
//        });
//        echo "Continue Handle Worker\n";
    }

    // public function onTick($timer_id, $params = null)
    // {
        // echo "Timer {$timer_id} running\n";
        // echo "Params: {$params}\n";
    // }
}
new Timer();